import Vue from 'vue'
import VueRouter from 'vue-router'
// import Home from '../views/Home.vue'
import { getToken } from '@/utils/storage'
Vue.use(VueRouter)

const routes = [
	{ path: '/detail/:id', component: () => import('../views/Detail.vue') },
	{
		path: '/login',
		name: 'Login',
		component: () => import('../views/Login.vue') //
	},
	{
		path: '/register',
		name: 'register',
		component: () => import('../views/Register.vue')
	},
	{
		path: '/',
		name: 'Layout',
		redirect: '/article',
		component: () => import('../views/Layout.vue'),
		children: [
			{
				path: '/article',
				name: 'Article',
				component: () => import('../views/Article.vue')
			},
			{
				path: '/collect',
				name: 'Collect',
				component: () => import('../views/Collect.vue')
			},
			{
				path: '/like',
				name: 'Like',
				component: () => import('../views/Like.vue')
			},
			{
				path: '/my',
				name: 'My',
				component: () => import('../views/My.vue')
			}
		]
	}
	// {
	//   path: '/about',
	//   name: 'About',
	//   // route level code-splitting
	//   // this generates a separate chunk (about.[hash].js) for this route
	//   // which is lazy-loaded when the route is visited.
	//   /*  */
	//   component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')//路由懒加载
	// }
]

const router = new VueRouter({
	routes
})

/* 路由导航守卫===路由钩子函数 路由地址发生改变就会触发钩子函数 */
// console.log(router, 777);
/* 前置 路由导守卫 跳转之前 */

const white = [ '/login', '/register' ] //没有token也可以访问

router.beforeEach((to, from, next) => {
	/* 需求：
有token就让你跳转，没有token不能跳转
但是：login、register 这两个页面 没有token也能跳转
*/
	var token = getToken()

	if (token) {
		console.log(token, '11token')
		next() //放行
	} else {
		console.log(token, '222token')
		//没有token 表示没有登录===去login
		if (white.includes(to.path)) {
			// 表示你现在要去的地址就是 login或者register
			next()
		} else {
			// 不是login或者register
			next('/login')
		}
		// next("/login");
	}

	// console.log(1111);
	// console.log(from.path, "from");
	// console.log(to.path, "to");
})

/*
区分 请求拦截器、路由拦截器
请求拦截器 axios====只要发送请求就跟请求拦截器=相关===只要发送请求，请求、响应拦截器就会生效
路由拦截器 router===只要路由值发生改变就会触发====钩子函数====只要路由切换就会触发钩子函数

*/

/* 后置 路由导守卫 跳转之前 */
// router.afterEach((to, from) => {
//   console.log(222);
//   console.log(from.path, "from");
//   console.log(to.path, "to");
// });

//保存原型对象的Push
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace
//重写push方法
VueRouter.prototype.push = function(location, res, rej) {
	if (res && rej) {
		originPush.call(this, location, res, rej)
	} else {
		originPush.call(this, location, () => {}, () => {})
	}
}
//重写replace方法
VueRouter.prototype.replace = function(location, res, rej) {
	if (res && rej) {
		originReplace.call(this, location, res, rej)
	} else {
		originReplace.call(this, location, () => {}, () => {})
	}
}

export default router
